//
// Copyright (c) Fela Ameghino 2015-2025
//
// Distributed under the GNU General Public License v3.0. (See accompanying
// file LICENSE or copy at https://www.gnu.org/licenses/gpl-3.0.txt)
//

using System;
using System.Threading.Tasks;
using Telegram.Common;
using Telegram.Navigation;
using Telegram.Navigation.Services;
using Telegram.Services;
using Telegram.Td.Api;
using Telegram.ViewModels.Delegates;
using Telegram.Views;
using Windows.UI.Xaml.Navigation;

namespace Telegram.ViewModels
{
    public partial class InstantViewModel : MultiViewModelBase
    {
        private readonly ITranslateService _translateService;

        private readonly IMessageDelegate _messageDelegate;

        public InstantViewModel(IClientService clientService, ISettingsService settingsService, IStorageService storageService, ITranslateService translateService, IEventAggregator aggregator)
            : base(clientService, settingsService, aggregator)
        {
            _translateService = translateService;
            _gallery = new InstantGalleryViewModel(clientService, storageService, aggregator);

            _messageDelegate = new InstantMessageDelegate(this);

            Children.Add(_gallery);
        }

        public ITranslateService TranslateService => _translateService;

        protected override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, NavigationState state)
        {
            if (parameter is InstantPageArgs args)
            {
                var response = await ClientService.SendAsync(new GetLinkPreview(new FormattedText(args.Url, Array.Empty<TextEntity>()), null));
                if (response is LinkPreview linkPreview)
                {
                    Title = linkPreview.SiteName;
                }
            }
        }

        public Uri ShareLink { get; set; }
        public string ShareTitle { get; set; }

        public MessageViewModel CreateMessage(Message message)
        {
            if (message == null)
            {
                return null;
            }

            return new MessageViewModel(ClientService, _messageDelegate, null, null, null, message, false);
        }

        private InstantGalleryViewModel _gallery;
        public InstantGalleryViewModel Gallery
        {
            get => _gallery;
            set => Set(ref _gallery, value);
        }

        private string _title;
        public string Title
        {
            get => _title;
            set => Set(ref _title, value);
        }

        public async void Feedback(INavigationService service)
        {
            var response = await ClientService.SendAsync(new SearchPublicChat("previews"));
            if (response is Chat chat)
            {
                service.NavigateToChat(chat);
            }
        }
    }
}
